package com.bgl.mall.util;

import com.bgl.mall.common.RedisPool;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * @author Bu Guoliang
 * @date 2019/07/06 13:37
 * @since 1.8
 */
@Slf4j
public class RedisPoolUtil {

    /**
     * @param key
     * @param value
     * @param exTime 单位是秒
     * @return
     */
    public static String setEx(String key, String value, int exTime){
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.setex(key, exTime, value);
        } catch (Exception e) {
            log.error("setex key:{}, value:{} error", key, value, e);
            jedis.close();
        }
        jedis.close();
        return result;
    }

    /**
     * @param key
     * @param exTime 单位是秒
     * @return
     */
    public static Long expire(String key, int exTime){
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.expire(key, exTime);
        } catch (Exception e) {
            log.error("expire key:{} error", key, e);
            jedis.close();
        }
        jedis.close();
        return result;
    }

    public static String set(String key, String value){
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.set(key, value);
        } catch (Exception e) {
            log.error("set key:{}, value:{} error", key, value, e);
            jedis.close();
        }
        jedis.close();
        return result;
    }

    public static String get(String key){
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            log.error("get key:{} error", key, e);
            jedis.close();
        }
        jedis.close();
        return result;
    }

    public static Long del(String key){
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.del(key);
        } catch (Exception e) {
            log.error("get key:{} error", key, e);
            jedis.close();
        }
        jedis.close();
        return result;
    }

    public static void main(String[] args) {
        System.out.println(set("bgl", "bgl123"));
        set("gg", "gg");
        System.out.println(get("bgl"));
        System.out.println(expire("bgl", 100));
        System.out.println(del("gg"));
    }
}
